<template>
  <div>
    <el-button type="success" round size="big" @click="makeNewSale">{{ $t('order.addNewOrder') }}</el-button>
    <div>
      <el-form ref="queryForm" :model="queryParams" :inline="true" label-width="68px">
        <el-form-item prop="saleNo">
          <el-input
            v-model="queryParams.saleNo"
            :placeholder="$t('order.Please enter saleNo')"
            prefix-icon="el-icon-search"
            style="width: 400px; margin-right: 50px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item prop="status">
          <el-select
            v-model="queryParams.status"
            clearable
            :placeholder="$t('order.orderStatus')"
            style="margin-right: 50px"
            @keyup.enter.native="handleQuery"
          >
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item prop="createTime">
          <el-select v-model="queryParams.timeRange" clearable :placeholder="$t('order.createTime')" style="margin-right: 30px">
            <el-option v-for="item in options1" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="info" round icon="el-icon-search" @click="handleQuery">{{ $t('order.search') }}</el-button>
          <el-button icon="el-icon-refresh" type="info" round @click="resetQuery">{{ $t('order.reset') }}</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div shadow="always" style="overflow: auto">
      <!-- 订单主页面table -->
      <template>
        <el-table v-loading="loading" :data="saleList" height="628" style="width: 100%">
          <el-table-column type="expand" header-align="center">
            <template slot-scope="scope">
              <div class="product-list">
                <div v-for="item in scope.row.saleClothes" :key="item.saleClothesId" class="product-info">
                  <img :src="item.clothesNorm.clothes.url" class="product-image">
                  <div class="product-details">
                    <div class="detail-item">{{ $t('order.clothesNumber') }}: {{ item.clothesNorm.clothes.clothesNumber }}</div>
                    <div class="detail-item">{{ $t('order.clothesName') }}: {{ item.clothesNorm.clothes.clothesName }}</div>
                    <div class="detail-item">{{ $t('order.size') }}: {{ item.clothesNorm.norm.size.sizeName }}</div>
                    <div class="detail-item">{{ $t('order.color') }}: {{ item.clothesNorm.norm.color.colorName }}</div>
                    <div class="detail-item">{{ $t('order.quantity') }}: {{ item.quantity }}</div>
                    <div class="detail-item">{{ $t('order.listPrice') }}: {{ item.clothesNorm.price }}</div>
                    <div class="detail-item">{{ $t('order.salePrice') }}: {{ item.price }}</div>
                    <div class="detail-item">{{ $t('order.status') }}:<el-tag>{{ item.status }}</el-tag></div>
                    <div class="detail-item"><el-tag v-if="item.clothesNorm.clothes.discountStatus === 'true'" type="success" effect="dark">75折</el-tag></div>
                    <div class="detail-item actions">
                      <el-button type="text" size="small" icon="el-icon-goods" @click="takeSomeBack(scope.row,item)">{{ $t('order.saleReturn') }}</el-button>
                      <el-button type="text" size="small" icon="el-icon-goods" @click="exchangeBake(scope.row,item)">{{ $t('order.saleExchange') }}</el-button>
                    </div>
                  </div>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column :label="$t('order.index')" prop="saleId" align="center" width="60px" />
          <el-table-column :label="$t('order.saleNo')" prop="saleNo" align="center" />
          <el-table-column :label="$t('order.amount')" align="center" prop="total" />
          <el-table-column :label="$t('order.orderDate')" align="center">
            <template slot-scope="scope">
              {{ formatDateTime(scope.row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column :label="$t('order.status')" align="center" prop="status" />
          <el-table-column :label="$t('order.operation')" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button type="text" size="small" icon="el-icon-edit" @click="cancelSale(scope.row)">{{ $t('order.cancel') }}</el-button>
              <el-button type="text" size="small" icon="el-icon-s-goods" @click="selectPayment(scope.row)">{{ $t('order.makePayment') }}</el-button>
              <el-button type="text" size="small" icon="el-icon-goods" @click="takeAllBack(scope.row)">{{ $t('order.saleReturn') }}</el-button>
            </template>
          </el-table-column>
        </el-table>
      </template>
      <el-dialog :visible.sync="dialogFormVisible" :title="$t('order.saleExchange')" width="500">
        <el-form :model="form">
          <el-form-item :label="$t('order.clothesName')">
            <el-input v-model="form.clothesName" disabled />
          </el-form-item>
          <el-form-item :label="$t('order.currentColor')">
            <el-input v-model="form.currentColor" disabled />
          </el-form-item>
          <el-form-item :label="$t('order.currentSize')">
            <el-input v-model="form.currentSize" disabled />
          </el-form-item>
          <el-form-item :label="$t('order.exchangeColor')">
            <el-radio-group v-model="form.newColor" @change="handleColorChange">
              <el-radio-button v-for="color in colors" :key="color.colorId" :label="color.colorId">
                {{ color.colorName }}
              </el-radio-button>
            </el-radio-group>
          </el-form-item>
          <el-form-item :label="$t('order.exchangeSize')">
            <el-radio-group v-model="form.newSize">
              <el-radio-button v-for="size in sizes" :key="size.sizeId" :label="size.sizeId" :disabled="!size.available">
                {{ size.sizeName }}
              </el-radio-button>
            </el-radio-group>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogFormVisible = false">{{ $t('order.cancel') }}</el-button>
            <el-button type="primary" @click="confirmExchange">{{ $t('order.confirm') }}</el-button>
          </div>
        </template>
      </el-dialog>
      <!-- 新建订单 -->
      <div class="dialog">
        <el-dialog :visible.sync="dialogVisible" :fullscreen="true">
          <div class="app-container">
            <el-container style="margin: 30px auto auto 15px">
              <el-aside width="500px">
                <el-card>
                  <div slot="header" class="title">{{ $t('order.Enter Goods') }}</div>
                  <el-form ref="enterItemForm" :model="enterItemForm" size="small" label-width="130px" style="margin-right: 30px">
                    <el-form-item :label="$t('order.clothesNumber')" prop="clothesNumber">
                      <el-input v-model="enterItemForm.clothesNumber" :placeholder="$t('order.Please enter clothesNumber')" clearable @keyup.enter.native="enterItem" />
                    </el-form-item>
                    <el-form-item :label="$t('order.color')">
                      <el-radio-group v-model="enterItemForm.colorId" @change="getNormSn">
                        <el-radio-button v-for="color in colorList" :key="color.colorId" :label="color.colorId" :value="color.colorId">
                          {{ color.colorName }}
                        </el-radio-button>
                      </el-radio-group>
                    </el-form-item>
                    <el-form-item :label="$t('order.size')">
                      <el-radio-group v-model="enterItemForm.sizeId" @change="getNormSn">
                        <el-radio-button v-for="size in sizeList" :key="size.sizeId" :label="size.sizeId" :value="size.sizeId">
                          {{ size.sizeName }}
                        </el-radio-button>
                      </el-radio-group>
                    </el-form-item>
                    <el-form-item :label="$t('order.quantity')" prop="quantity">
                      <el-input v-model="enterItemForm.quantity" clearable @keyup.enter.native="enterItem" />
                    </el-form-item>
                    <el-form-item v-show="false" :label="$t('order.salePrice')" prop="price">
                      <el-input v-model="enterItemForm.price" disabled clearable @keyup.enter.native="getCurrentPrice" />
                    </el-form-item>
                    <el-form-item label-width="0">
                      <el-button type="primary" style="margin-left: 50px" @click="enterItem">{{ $t('order.confirm') }}</el-button>
                      <el-button type="warning" style="margin-left: 50px" @click="endSale">{{ $t('order.endSale') }}</el-button>
                    </el-form-item>
                  </el-form>
                </el-card>
              </el-aside>
              <el-main>
                <el-descriptions :column="3" border>
                  <el-descriptions-item :label="$t('order.member')">张三</el-descriptions-item>
                  <el-descriptions-item :label="$t('order.saleNo')">{{ orderInfo.saleNo }}</el-descriptions-item>
                  <el-descriptions-item :label="$t('order.amount')">{{ totalSum }}</el-descriptions-item>
                  <el-descriptions-item :label="$t('order.quantity')">{{ totalQuantity }}</el-descriptions-item>
                  <el-descriptions-item :label="$t('order.createTime')">{{ orderInfo.createTime }}</el-descriptions-item>
                  <el-descriptions-item :label="$t('order.status')"><el-tag size="small">{{ orderInfo.status }}</el-tag></el-descriptions-item>
                  <el-descriptions-item :label="$t('order.label')">暂无</el-descriptions-item>
                </el-descriptions>
                <el-card class="card">
                  <div slot="header" class="title">{{ $t('order.orderDetails') }}</div>
                  <!-- 新建订单 -->
                  <el-table
                    :data="saleItemList"
                    stripe
                    style="width: 100%"
                  >
                    <el-table-column :label="$t('order.index')" width="100" align="center">
                      <template slot-scope="scope">
                        {{ scope.$index + 1 }}
                      </template>
                    </el-table-column>
                    <el-table-column prop="clothesNumber" :label="$t('order.clothesNumber')" align="center" />
                    <el-table-column width="50px">
                      <template v-slot="scope">
                        <el-tag v-show="scope.row.discountStatus" type="success" effect="dark">75折</el-tag>
                      </template>
                    </el-table-column>
                    <el-table-column prop="clothesName" :label="$t('order.clothesName')" align="center" />
                    <el-table-column prop="colorName" :label="$t('order.color')" align="center" />
                    <el-table-column prop="sizeName" :label="$t('order.size')" align="center" />
                    <el-table-column prop="initialPrice" :label="$t('order.listPrice')" align="center" />
                    <el-table-column prop="price" :label="$t('order.salePrice')" align="center" />
                    <el-table-column prop="quantity" :label="$t('order.quantity')" width="150px" align="center">
                      <template slot-scope="scope">
                        <el-input-number v-model="scope.row.quantity" size="mini" :min="1" :max="10" style="margin-right:50px" @change="handleChangeQuantity(scope.row)" />
                      </template>
                    </el-table-column>
                    <el-table-column fixed="right" :label="$t('order.operation')" align="center" class-name="small-padding fixed-width">
                      <template slot-scope="scope">
                        <el-button type="text" size="small" icon="el-icon-delete-solid" @click="handleDelete(scope.row)">{{ $t('order.cancel') }}</el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                </el-card>
              </el-main>
            </el-container>
          </div>
        </el-dialog>
      </div>
      <!-- 支付表单 -->
      <div>
        <el-dialog :visible.sync="paymentDialogVisible" :title="$t('order.paymentTitle')">
          <el-form label-width="100px">
            <el-form-item :label="$t('order.saleNo')">{{ orderInfo.saleNo }}</el-form-item>
            <el-form-item :label="$t('order.amount')">{{ orderInfo.totalSum }}</el-form-item>
            <el-form-item :label="$t('order.quantity')">{{ orderInfo.totalQuantity }}</el-form-item>
            <el-form-item :label="$t('order.createTime')">{{ orderInfo.createTime }}</el-form-item>
            <el-form-item :label="$t('order.status')">{{ orderInfo.status }}</el-form-item>
            <el-form-item :label="$t('order.paymentMethod')">
              <el-radio-group v-model="paymentRadio">
                <el-radio label="cash" size="large" border>{{ $t('order.cashPayment') }}</el-radio>
                <el-radio label="alipay" size="large" border @change="makePaymentByAliPay()">{{ $t('order.alipayPayment') }}</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form ref="makePaymentForm" :model="makePaymentForm" size="small" label-width="68px">
              <el-form-item v-if="paymentRadio === 'cash'" :label="$t('order.amountPaid')" prop="cashTendered">
                <el-input v-model="makePaymentForm.cashTendered" />
              </el-form-item>
              <el-form-item v-if="paymentRadio === 'cash'" :label="$t('order.change')">
                <el-input v-model="changeDue" disabled />
              </el-form-item>
              <el-form-item>
                <el-button v-if="paymentRadio === 'cash'" type="danger" size="mini" @click="makePayment()">{{ $t('order.confirmPayment') }}</el-button>
              </el-form-item>
            </el-form>
          </el-form></el-dialog></div>
      <!-- 分页加载 -->
      <el-pagination
        :page-size="queryParams.pageSize"
        :current-page="queryParams.pageNum"
        :page-sizes="[10,20,30,40]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>  
  <script>
              import {
              listSaleByPage,
              getSaleList,
              enterItem,
              makeNewSale,
              endSale,
              makePayment,
              cancelSale,
              getColorList,
              getSizeList,
              deleteSaleItem,
              listNormByColorAndSize,
              getDiscountPrice,
              returnBack,
              exchange
              } from '@/api/sale'
              import { getClothesNormList } from '@/api/oss'
              import { getClothesList } from '@/api/clothes'
              export default {
              data() {
              return {
              totalPrice: 0,
              clothesPrice: 0,
              discountVisible: false,
              dialogVisible: false,
              dialogFormVisible: false,
              paymentDialogVisible: false,
              total: 0,
              changeDue: 0,
              clothesNumberSelected: '',
              saleClothesSelect: 0,
              clothesNormSelected: 0,
              form: {
              colorId: '',
              sizeId: ''
              },
              allSizes: [], // 存储所有尺码
              saleItems: [],
              saleData: [],
              saleItemList: [],
              currentSaleList: [],
              clothesNormListBycn: [],
              showSaleList: false,
              orderInfo: {
              createTime: null
              },
              saleList: [],
              enterItemForm: {},
              selectedColor: '', // 选中的颜色
              selectedSize: '',
              colors: [],
              sizes: [],
              paymentRadio: 'cash',
              makePaymentForm: {},
              queryParams: {
              // 查询参数
              pageNum: 1,
              pageSize: 10,
              saleNo: '',
              status: '',
              timeRange: null,
              startTime: '',
              endTime: ''
              },
              colorList: [],
              sizeList: [],
              options: [
              {
              value: '已预定',
              label: '已预定'
              },
              {
              value: '已付款',
              label: '已付款'
              },
              {
              value: '已取消',
              label: '已取消'
              },
              {
              value: '已退款',
              label: '已退款'
              },
              {
              value: '部分退款',
              label: '部分退款'
              }
              ],
              options1: [
              {
              value: '选项1',
              label: '三天内'
              },
              {
              value: '选项2',
              label: '一个月内'
              },
              {
              value: '选项3',
              label: '三个月内'
              },
              {
              value: '选项4',
              label: '一年内'
              }
              ]
              }
              },
              computed: {
              totalQuantity() {
              return this.saleItemList.reduce((sum, item) => sum + item.quantity, 0)
              },
              totalSum() {
              return this.saleItemList.reduce((sum, item) => sum + item.quantity * item.price, 0)
              },
              filteredSaleItemList() {
              return this.saleItemList.filter(item => item.isDelete === 0)
              }
              },
              created() {
              this.getSaleList()
              this.getColorList()
              this.getSizeList()
              },
              methods: {
              getSaleList() {
              this.loading = true
              listSaleByPage(this.queryParams).then((response) => {
              console.log('Response:', response) // 调试输出
              this.saleList = response.data.list
              this.total = response.data.total
              this.loading = false
              }).catch((error) => {
              console.error('Error fetching data:', error) // 错误输出
              this.loading = false
              })
              },
              handleSizeChange(val) {
              this.queryParams.pageSize = val
              this.getSaleList()
              },
              handleCurrentChange(val) {
              this.queryParams.pageNum = val
              this.getSaleList()
              },
              handleQuery() {
              this.queryParams.pageNum = 1
              this.getSaleList() 
              },
              resetQuery() {
              this.$refs.queryForm.resetFields()
              this.getSaleList()
              },
              makeNewSale() {
              this.clear()
              makeNewSale().then(response => {
              this.dialogVisible = true
              this.step = 2
              this.orderInfo = response.data
              this.setCreateTime()
              })
              },
              // 步骤2：提交输入商品
              async getCurrentPrice() {
              console.log('开始调用getCurrentPrice')
              const clothesNumber = this.enterItemForm.clothesNumber
              try {
              const clothesNormResponse = await getClothesNormList({})
              const clothesNormData = clothesNormResponse.data
              for (const item of clothesNormData) {
              if (item.clothesNumber === clothesNumber) {
              this.clothesPrice = item.price
              console.log('clothesPrice', this.clothesPrice)
              break
              }
              }
              const clothesResponse = await getClothesList({})
              const clothesData = clothesResponse.data
              for (const item of clothesData) {
              if (item.clothesNumber === clothesNumber) {
              const clothesStatus = item.discountStatus === 'true'
              console.log('该商品打折状态', clothesStatus)

              if (clothesStatus) {
              // 如果有折扣，获取折扣价格
              const discountResponse = await getDiscountPrice(this.clothesPrice)
              this.enterItemForm.price = discountResponse.data
              console.log('打折', this.enterItemForm.price)
              } else {
              this.enterItemForm.price = this.clothesPrice
              console.log('没打折', this.enterItemForm.price)
              }
              break
              }
              }
              } catch (error) {
              console.error('获取价格失败:', error)
              this.$message.error('获取价格失败')
              }
              },
              async enterItem() {
              console.log('enterItemForm', this.enterItemForm)
              await this.getCurrentPrice()
              enterItem(this.enterItemForm).then(response => {
              if (response.code === 200) {
              const newItem = response.data // 新增的商品信息
              console.log('newItem', newItem)
              this.discountVisible = JSON.parse(newItem.discountStatus)
              this.saleData = {
              clothesNumber: newItem.clothesNumber,
              discountStatus: this.discountVisible,
              clothesName: newItem.clothesName,
              initialPrice: this.clothesPrice,
              price: newItem.price,
              quantity: newItem.quantity,
              colorName: this.selectedColor,
              sizeName: this.selectedSize
              }
              const existingItemIndex = this.saleItemList.findIndex(item =>
              item?.clothesNumber === newItem.clothesNumber &&
              item?.sizeName === this.selectedSize &&
              item?.colorName === this.selectedColor
              )
              if (existingItemIndex === -1) {
              this.saleItemList.push(this.saleData) // 如果不存在相同商品，则添加到订单明细中
              } else {
              // 如果存在相同商品，则更新数量
              this.saleItemList[existingItemIndex].quantity += newItem.quantity
              }
              } else {
              this.$message.error(response.msg) // 处理错误情况
              }
              }).catch(error => {
              console.error('添加商品失败:', error)
              this.$message.error('添加商品失败')
              })
              },

              // 步骤3：结束输入
              endSale() {
              endSale().then((response) => {
              this.dialogVisible = false
              this.orderInfo.total = response.data
              })
              const sum = 0
              this.saleItemList.map((item) => item.quantity + sum)
              this.orderInfo.quantity = sum
              },
              selectPayment(row) {
              if (row.status !== '已预定') {
              this.$message.error('只有状态为"已预定"的订单才能进行支付')
              return
              }
              this.paymentDialogVisible = true
              this.showSaleList = true
              this.orderInfo.saleNo = row.saleNo
              this.orderInfo.totalSum = row.total
              this.totalPrice = row.total
              this.orderInfo.createTime = row.createTime
              // 获取当前行的数据
              this.saleItems = this.getSaleItems(row.saleNo)
              this.orderInfo.totalQuantity = this.saleItems.reduce((sum, item) => sum + item.quantity, 0)
              this.orderInfo.status = row.status
              },
              // 步骤4：提交支付
              makePayment() {
              const saleData = { saleId: this.saleItems[0].saleId }
              const cashTendered = parseFloat(this.makePaymentForm.cashTendered)
              if (this.makePaymentForm.cashTendered > this.totalSum) {
              makePayment(saleData, cashTendered).then((response) => {
              this.changeDue = response.data
              }).then(() => {
              this.getSaleList()
              this.$message.success('支付成功')
              this.paymentDialogVisible = false
              }).then(() => {

              })
              } else {
              this.$message.warning('付款金额小于订单总金额')
              this.paymentDialogVisible = false
              }
              },
              makePaymentByAliPay(){
              const saleId = this.saleItems[0].saleId
              window.open(`http://localhost:8088/sale/alipay?saleId=${saleId}`)
              .catch(error => {
              // 处理错误情况
              console.error('支付宝付款失败', error)
              })
              },
              getSaleItems(saleNo) {
              const sale = this.saleList.find(sale => sale.saleNo === saleNo)
              return sale ? sale.saleClothes : []
              },
              clear() {
              this.orderInfo = {}
              this.saleItemList = []
              this.enterItemForm = {
              clothesNumber: '',
              quantity: 1,
              price: 0
              }
              this.makePaymentForm = {
              cashTendered: 0
              }
              this.changeDue = 0
              this.step = 1
              },
              // 为table订单明细添加序号
              rowSaleItemIndex({ row, rowIndex }) {
              row.index = rowIndex + 1
              },
              cancelSale(row) {
              if (row.status !== '已预定') {
              this.$message.error('只有状态为"已预定"的订单才能取消')
              return
              }
              const saleId = row.saleId
              this.$confirm('是否确认取消订单号为"' + saleId + '"的订单?', '警告', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
              })
              .then(() => {
              return cancelSale({ saleId }) // Passing ID directly
              })
              .then(() => {
              this.getSaleList() // 更新销售列表
              this.$message.success('取消成功') // 显示成功消息
              })
              .catch(error => {
              // 处理错误情况
              console.error('取消订单失败:', error)
              this.$message.error('取消失败')
              })
              },
              // 删除订单明细
              delSaleItem(row){
              const delId = row.saleClothesId
              this.$confirm('是否确认删除ID为"' + delId + '"的数据项?', '警告', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
              })
              .then(() => {
              row.isDelete = 1
              this.$message.success('删除成功')
              return deleteSaleItem({ saleClothesId: delId }) // Passing ID directly
              })
              .catch(() => {
              this.$message.error('删除失败')
              })
              },
              // 退货
              takeAllBack(row){
              if (row.status !== '已付款') {
              this.$message.error('只有已付款的订单才能进行售后服务')
              return
              }
              const currentDate = new Date()
              const sevenDaysAgo = new Date(currentDate)
              sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 7)
              const orderCreateTime = new Date(row.createTime)
              if (orderCreateTime < sevenDaysAgo) {
              this.$message.error('订单已超出七天无理由售后服务时间，无法售后')
              return
              }
              const saleId = row.saleId
              this.$confirm('是否确认退货退款该订单的全部商品?' + '退款金额为' + row.total + '。', '警告', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
              }).then(() => {
              return returnBack({ saleId })
              }).then(() => {
              this.getSaleList() // 更新销售列表
              this.$message.success('退货退款成功') // 显示成功消息
              })
              .catch(error => {
              // 处理错误情况
              console.error('退货退款订单失败:', error)
              this.$message.error('退货退款失败')
              })
              },
              takeSomeBack(row, item){
              if (item.status !== '已付款') {
              this.$message.error('只有已付款的订单才能进行售后服务')
              return
              }
              const currentDate = new Date()
              const sevenDaysAgo = new Date(currentDate)
              sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 7)
              const orderCreateTime = new Date(row.createTime)
              if (orderCreateTime < sevenDaysAgo) {
              this.$message.error('订单已超出七天无理由售后服务时间，无法售后')
              return
              }
              const saleId = row.saleId
              const saleClothes = [item]
              const clothesName = item.clothesNorm.clothes.clothesName
              this.$confirm('是否确认退货商品名为"' + clothesName + '"的商品,' + '退款金额为' + item.price + '。', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
              }).then(() => {
              const returnSomeBake = { saleId, saleClothes }
              console.log('returnSomeBack', returnSomeBake)
              return returnBack(returnSomeBake)
              }).then(() => {
              this.getSaleList() // 更新销售列表
              this.$message.success('退货退款成功') // 显示成功消息
              }).catch(error => {
              // 处理错误情况
              console.error('退货退款订单失败:', error)
              this.$message.error('退货退款失败')
              })
              },
              // 换货
              async exchangeBake(row, item) {
              if (row.status !== '已付款') {
              this.$message.error('只有已付款的订单才能进行售后服务')
              return
              }
              const currentDate = new Date()
              const sevenDaysAgo = new Date(currentDate)
              sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 7)
              const orderCreateTime = new Date(row.createTime)
              if (orderCreateTime < sevenDaysAgo) {
              this.$message.error('订单已超出七天无理由售后服务时间，无法售后')
              return
              }
              this.form.colorId = null
              this.form.sizeId = null
              this.saleClothesSelect = item.saleClothesId
              this.clothesNumberSelected = item.clothesNorm.clothes.clothesNumber
              const clothesNumber = item.clothesNorm.clothes.clothesNumber
              this.form.clothesName = item.clothesNorm.clothes.clothesName
              this.form.currentSize = item.clothesNorm.norm.size.sizeName
              this.form.currentColor = item.clothesNorm.norm.color.colorName
              this.dialogFormVisible = true
              try {
              const response = await getClothesNormList({ clothesNumber })
              this.clothesNormListBycn = response.data
              this.refineColors(this.clothesNormListBycn)
              this.refineAllSizes(this.clothesNormListBycn)
              this.updateSizes() // 初始化时更新尺码列表
              } catch (error) {
              console.error('Error fetching clothesNorm:', error)
              }
              },
              refineColors(clothesNormListBycn) {
              const colorSet = new Set()
              clothesNormListBycn.forEach(item => {
              if (item.norm && item.norm.color && item.norm.color.colorId && item.norm.color.colorName) {
              colorSet.add(JSON.stringify({ colorId: item.norm.color.colorId, colorName: item.norm.color.colorName }))
              }
              })
              this.colors = Array.from(colorSet).map(color => JSON.parse(color))
              },
              refineAllSizes(clothesNormListBycn) {
              const sizeSet = new Set()
              clothesNormListBycn.forEach(item => {
              if (item.norm && item.norm.size && item.norm.size.sizeId && item.norm.size.sizeName) {
              sizeSet.add(JSON.stringify({ sizeId: item.norm.size.sizeId, sizeName: item.norm.size.sizeName }))
              }
              })
              this.allSizes = Array.from(sizeSet).map(size => JSON.parse(size))
              },
              handleColorChange() {
              this.updateSizes()
              },
              updateSizes() {
              const selectedColor = this.form.newColor
              const availableSizes = new Set()

              this.clothesNormListBycn.forEach(item => {
              if (item.norm && item.norm.color.colorId === selectedColor) {
              availableSizes.add(item.norm.size.sizeId)
              }
              })

              this.sizes = this.allSizes.map(size => ({
              ...size,
              available: availableSizes.has(size.sizeId)
              }))
              },
              confirmExchange() {  
              const colorId = this.form.newColor  
              const sizeId = this.form.newSize
              console.log('COLOR', colorId, 'size', sizeId)
              listNormByColorAndSize({ colorId, sizeId }).then(response => {  
              const data = response.data  
              const normSn = data[0].normSn  
              const clothesNumber = this.clothesNumberSelected  
              const clothesNormData = { clothesNumber, normSn }  
              return getClothesNormList(clothesNormData).then(response => { // 注意这里的 return  
              const data = response.data  
              this.clothesNormSelected = data[0].clothesNormId  
              console.log('data', data)  
              console.log('kucunId', this.clothesNormSelected)  
              const exchangeData = {  
              saleClothesId: this.saleClothesSelect,
              clothesNormId: this.clothesNormSelected  
              }  
              console.log('exchangeData', exchangeData)
              this.dialogFormVisible = false
              this.form.colorName = ''
              this.form.sizeName = ''
              return exchange(exchangeData) 
              }).then(() => {
              this.getSaleList() // 更新销售列表
              this.$message.success('换货成功') // 显示成功消息
              }).catch(error => {  
              console.error('An error occurred:', error)  
              })  
              }).catch(error => {  
              console.error('An error occurred in listNormByColorAndSize:', error)  
              }).catch(error => {
              // 处理错误情况
              console.error('换货失败:', error)
              this.$message.error('换货失败')
              })
              },
              getColorList() {
              // this.loading = true
              getColorList({}).then(response => {
              this.colorList = response.data
              })
              },
              getSizeList() {
              // this.loading = true
              getSizeList({}).then(response => {
              this.sizeList = response.data
              })
              },
              getNormSn() {
              const colorId = this.enterItemForm.colorId
              const sizeId = this.enterItemForm.sizeId
              listNormByColorAndSize({ colorId, sizeId }).then(response => {
              const data = response.data
              if (data && data.length > 0) {
              this.enterItemForm.normSn = data[0].normSn
              this.selectedColor = this.colorList.find(color => color.colorId === colorId).colorName
              this.selectedSize = this.sizeList.find(size => size.sizeId === sizeId).sizeName
              } else {
              this.enterItemForm.normSn = ''
              this.selectedColor = '' // 如果没有找到符合条件的规格，清空选中的颜色
              this.selectedSize = '' // 如果没有找到符合条件的规格，清空选中的尺码
              this.$message.error('未找到相应的规格编号')
              }
              }).catch(error => {
              console.error('获取normSn失败:', error)
              })
              },
              setCreateTime() {
              this.orderInfo.createTime = new Date().toLocaleString() // 获取当前时间并转换为字符串
              },
              // 修改时间格式
              formatDateTime(dateTimeStr) {
              const date = new Date(dateTimeStr)
              const year = date.getFullYear()
              const month = String(date.getMonth() + 1).padStart(2, '0')
              const day = String(date.getDate()).padStart(2, '0')
              const hours = String(date.getHours()).padStart(2, '0')
              const minutes = String(date.getMinutes()).padStart(2, '0')
              const seconds = String(date.getSeconds()).padStart(2, '0')
              return `${year}/${month}/${day} ${hours}:${minutes}:${seconds}`
              }
              }
              }
            </script>

            <style scoped lang="css">
              .el-aside {
              box-shadow: 3px #ccc;
              }

              .demo-table-expand .el-form-item {
              margin-right: 0;
              margin-bottom: 0;
              width: 50%;
              }

              .table {
              margin-left: 0px;
              width: 800px;
              place-items: center;
              }

              .el-descriptions-item {
              margin-top: 50px;
              box-shadow: 0 0 2px 2px #ccc;
              }

              .title {
              text-align: center;
              font-size: 20px;
              font-family: "微软雅黑";
              font-weight: bold;
              line-height: 30px;
              }

              .sale_item {
              box-shadow: 0 0 3px 3px #ccc;
              width: 100%;
              margin-top: 20px;
              margin-bottom: 20px;
              margin-left: 50px;
              }

              .dialog {
              height: 100%;
              width: 100%;
              }

              .list {
              width: 100%;
              margin-top: 30px;
              box-shadow: 0 0 3px 3px #ccc;
              }

              .search {
              margin-top: 150px;
              margin-left: 500px;
              }

              .search .el-input__inner {
              border: 0;
              border-bottom-width: 1px;
              border-bottom: solid gray;
              }

              .product-list {
              display: flex;
              flex-wrap: wrap; /* 允许商品信息换行 */
              }

              .product-info {
              display: inline-flex;
              align-items: center;
              margin-right: 20px; /* 增加每个商品之间的水平间距 */
              }

              .product-image {
              width: 80px;
              margin-right: 20px;
              }

              .product-details {
              display: flex;
              flex-direction: column;
              }

              .detail-item {
              margin-bottom: 5px;
              }

              .actions {
              display: flex;
              gap: 10px;
              margin-top: 10px; /* 增加操作按钮与其他详情项的间距 */
              }
              .el-table__header-wrapper th:nth-child(7) {
              text-align: center;
              }
            </style>
